<template>

  <div class="progress-bar-container">
    <div class="progress-info">
      <span>进度：{{ allCount-unfinishedCount }}/{{ allCount }}</span>
      <span>百分比：{{ formattedPercentage }}%</span>
      <span>总字数：{{ wordCount }}</span>
    </div>

      <div class="reading-controls">
        <span>关键词朗读</span>
        <el-select
          v-model="readingRealm"
          placeholder="请选择朗读领域"
          multiple
          filterable
          class="custom-select-width">
          <el-option
            v-for="realmItem in realms"
            :key="realmItem"
            :label="realmItem"
            :value="realmItem"></el-option>
        </el-select>

        <el-button @click="readContent" type="primary" class="read-button">
          朗读
        </el-button>
        <el-button @click="stopReading" type="danger">停止</el-button>


      </div>

      
  </div>

  <div class="realm-section">
    <div class="realm-tags">
      <div
        v-for="(realm, index) in realmData"
        :key="realm.realm"
        class="realm-item"
        :class="{ 'selected': selectedRealm === realm.realm }"
        @click="selectRealm(realm.realm)"
        v-show="isExpanded || index === 0"
      >
        <span class="realm-name">{{ realm.realm }}</span>
        <div class="realm-stats">
          <span class="count-info">{{ realm.finishedCount + realm.unfinishedCount }}/{{ realm.finishedCount }}</span>
          <span class="word-count">{{ realm.wordCount }} 字</span>
        </div>
      </div>
    </div>
    <button @click="toggleExpansion" class="toggle-button">
      {{ isExpanded ? '隐藏...' : '展开...' }}
    </button>
  </div>

  <div class="data-list">

    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="search.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="领域">
        <el-input v-model="search.realm" placeholder="请输入领域"></el-input>
      </el-form-item>
      <el-form-item label="含义">
        <el-input v-model="search.meaning" placeholder="请输入含义"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchKeywords">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="showAddKeywordDialog">新建关键字</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-button type="primary" @click="showAddKeywordDialog" style="margin-bottom: 20px;">新建关键字</el-button> -->


    <el-table 
      :data="tableData" 
      style="width: 100%"
      @sort-change="handleSortChange"
      >
      <el-table-column prop="name" label="关键词" width="200" align="center"></el-table-column>
      <el-table-column prop="realm" label="领域" width="100" align="center" sortable></el-table-column>
      <el-table-column prop="meaning" label="含义" width="meaningWidth" align="left">
        <template #default="scope">
          <span style="white-space: pre-line;">{{ scope.row.meaning }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否朗读" width="100" align="center">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.isReading === 1"
            @change="toggleReadingStatus(scope.row, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" key="slot">
        <template #default="scope">
            <el-button @click="showUpdateKeywordDialog(scope.row)" type="primary">修改关键词</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;"
    ></el-pagination>

    <!-- 修改关键词的对话框 -->
    <!-- 修改关键词的对话框 -->
<el-dialog 
  title="修改关键词" 
  modal-append-to-body
  v-model="dialogVisible"
  width="50%">
  <el-form :model="editKeywordForm" label-width="100px">
    <el-form-item label="名称">
      <el-input v-model="editKeywordForm.name" placeholder="请输入名称" clearable></el-input>
    </el-form-item>
    <el-form-item label="领域">
      <el-input v-model="editKeywordForm.realm" placeholder="请输入领域" clearable></el-input>
    </el-form-item>
    <el-form-item label="含义">
      <el-input 
        v-model="editKeywordForm.meaning" 
        placeholder="请输入含义" 
        type="textarea"
        :rows="4"
        clearable></el-input>
    </el-form-item>
    <el-form-item label="行为ID">
      <el-autocomplete
        v-model="editKeywordForm.behaviorQuery"
        :fetch-suggestions="fuzzySearchBehavior"
        placeholder="请输入行为名称"
        @select="handleSelectBehaviorEdit"
      ></el-autocomplete>
      <el-select v-model="editKeywordForm.behaviorIds" multiple placeholder="请选择行为ID">
        <el-option
          v-for="item in searchBehaviorResults"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="相关关键词ID">
      <el-select
        v-model="editKeywordForm.keywordQuery"
        :remote-method="fuzzySearchKeyword"
        placeholder="请输入关键词名称"
        filterable
        remote
        multiple
      >
      <!-- TODO 增加删除关键词代码 -->
      <el-option
            v-for="item in this.searchKeywordResults"
            :key="item.id"
            :label="item.value"
            :value="item"
            @click.native="handleEditSelectKeyword(item)"

          />
      </el-select>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="confirmUpdateKeyword">确 定</el-button>
  </span>
</el-dialog>

    <!-- 添加关键词的对话框 -->
    <el-dialog 
      title="添加关键词" 
      modal-append-to-body
      v-model="addKeywordDialogVisible"
      width="50%">
      <el-form :model="addKeywordForm" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="addKeywordForm.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="领域">
          <el-input v-model="addKeywordForm.realm" placeholder="请输入领域" clearable></el-input>
        </el-form-item>
        <el-form-item label="含义">
          <el-input 
            v-model="addKeywordForm.meaning" 
            placeholder="请输入含义" 
             type="textarea"
            :rows="4"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="行为ID">
          <el-autocomplete
            v-model="addKeywordForm.behaviorQuery"
            :fetch-suggestions="fuzzySearchBehavior"
            placeholder="请输入行为名称"
            @select="handleSelectBehavior"
          ></el-autocomplete>
          <el-select v-model="addKeywordForm.behaviorIds" multiple placeholder="请选择行为ID">
            <el-option
              v-for="item in searchBehaviorResults"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="相关关键词ID">
          <el-select
            v-model="addKeywordForm.keywordQuery"
            :remote-method="fuzzySearchKeyword"
            placeholder="请输入关键词名称"
            filterable
            remote
            multiple
          >
          
          <el-option
            v-for="item in this.searchKeywordResults"
            :key="item.id"
            :label="item.value"
            :value="item"
            @click.native="handleSelectKeyword(item)"

          />

          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addKeywordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddKeyword">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 自定义弹窗组件 -->
    <el-dialog 
      title="朗读内容" 
      modal-append-to-body
      v-model="readingDialogVisible"
      width="50%">
      <span slot="footer" class="dialog-footer">
        <el-button @click="readingDialogVisible = false">确 定</el-button>
        <el-button @click="copyReadingContent" type="success">复制</el-button>

      </span>
      
      <pre>{{ readingContent }}</pre>
      
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import ElementUI from 'element-plus';
import { getRequest, postRequest, putRequest } from '../utils/request';

export default {
  data() {
    return {
      tableData: [],
      readTableData:[],
      dialogVisible: false,
      currentRow: null,
      newKeyword: '',
      sort:'create_time',
      sortOrder:'desc',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      addKeywordDialogVisible: false,
      addKeywordForm: {
        name: '',
        realm: '',
        meaning: '',
        behaviorIds: [],
        relationKeywordIds: [],
        keywordQuery:[],
        behaviorQuery:[],
        keywordQueryItems:[]
      },
      behaviorOptions: [],
      keywordOptions: [],
      searchBehaviorResults: [],
      searchKeywordResults: [],
      editKeywordForm: {
        id: null,
        name: '',
        realm: '',
        meaning: '',
        behaviorIds: [],
        relationKeywordIds: [],
        behaviorQuery: [],
        keywordQuery: []
      },
      search: {
        name: '',
        realm: '',
        meaning:''
      },
      wordCount :0,
      allCount: 0,
      unfinishedCount: 0,
      realms: [],
      realmData: [], // 存储领域详细数据
      selectedRealm: '',
      isExpanded: false,
      screenWidth: window.innerWidth,
      meaningWidth:0,
      readingRealm:[],
      toReadRealm:'',
      readingContent:'',
      isReading: false,
      readingDialogVisible: false
    };
  },
  created() {
    // 检查是否已登录
    const accessToken = localStorage.getItem('accessToken');
    if (!accessToken) {
      this.$router.push('/login'); // 如果未登录，跳转到登录页面
      return;
    }

    // 设置axios拦截器，自动添加access-token
    axios.interceptors.request.use(
      (config) => {
        config.headers['access-token'] = accessToken;
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    this.fetchData(this.currentPage,this.pageSize,this.sort,this.sortOrder,this.search.name,this.search.realm,this.search.meaning);
    this.fetchFinishStatus();
    this.fetchRealms();
    this.isExpanded = false;
    this.screenWidth = window.innerWidth;
    this.meaningWidth=this.screenWidth-450;
  },
  computed: {
    finishedCount() {
      return this.allCount - this.unfinishedCount;
    },
    formattedPercentage() {
      if (this.allCount === 0) return '0.00';
      return ((this.allCount - this.unfinishedCount) / this.allCount * 100).toFixed(2);
    }
  },
  methods: {
    fetchData(currentPage,pageSize,sort,sortOrder,name,realm,meaning) {
      try{
        postRequest('/keywords/all',{
          page:currentPage,
          pageSize:pageSize,
          sort:sort,
          sortOrder:sortOrder,
          name:name,
          realm:realm,
          meaning:meaning
        })
          .then(response => {
            console.log(response.data)
            this.tableData = response.data.items;
            this.total = response.data.total;
          })
       } catch (error) {
          if (error.response?.status === 401) {
            this.$message.error('登录已过期，请重新登录');
            localStorage.removeItem('accessToken');
            this.$router.push('/login');
          } else {
            console.error('获取数据失败:', error);
          }
      }
    },
    copyReadingContent() {
      if (!this.readingContent) return;

      navigator.clipboard.writeText(this.readingContent)
        .then(() => {
          this.$message.success('内容已复制到剪贴板');
        })
        .catch(err => {
          console.error('无法复制内容: ', err);
          this.$message.error('复制失败');
        });
    },
    async readContent() {
      this.isReading = true;
      console.log("readingRealm为", this.readingRealm);

      for (const toReadRealm of this.readingRealm) {
        // 把所有的朗读内容拼接成文字，在页面弹窗出来
        let readingContent = `开始阅读领域 ${toReadRealm}\n`;
        this.readTableData.forEach(item => {
          readingContent += `关键词为 ${item.name}\n含义为 ${item.meaning}\n\n`;
        });

        // // 使用 this.$alert 弹窗显示
        // this.$alert(readingContent, '朗读内容', {
        //   confirmButtonText: '确定',
        //   dangerouslyUseHTMLString: true
        // });
        // 使用自定义弹窗显示
        this.readingContent = readingContent;
        this.readingDialogVisible = true;

      }

      for (const toReadRealm of this.readingRealm) {
        if (!this.isReading) break;
        // 请求内容
        const response = await postRequest('/keywords/all', {
          page: 1,
          pageSize: 10000,
          sort: null,
          sortOrder: null,
          name: null,
          realm: toReadRealm,
          meaning: null
        });

        console.log(" 请求阅读内容response.data为", response.data);
        this.readTableData = response.data.items;

        
        // 定义一个函数来递归地朗读所有内容
        const speakItems = async (items) => {
          for (const item of items) {
            if (!this.isReading) break;
            await new Promise((resolve) => {
              const utterance = new SpeechSynthesisUtterance();
              utterance.lang = 'zh-CN';
              utterance.rate = 1;
              utterance.pitch = 1;
              utterance.volume = 1;

              // 设置文本并开始朗读
              utterance.text = `关键词为 ${item.name}`;
              window.speechSynthesis.speak(utterance);

              // 监听朗读结束事件
              utterance.onend = () => {
                console.log(`朗读完毕: ${utterance.text}`);
                resolve();
              };
            });

            if (!this.isReading) break;

            await new Promise((resolve) => {
              const utterance = new SpeechSynthesisUtterance();
              utterance.lang = 'zh-CN';
              utterance.rate = 1;
              utterance.pitch = 1;
              utterance.volume = 1;

              // 设置文本并开始朗读
              utterance.text = `含义为 ${item.meaning}`;
              window.speechSynthesis.speak(utterance);

              // 监听朗读结束事件
              utterance.onend = () => {
                console.log(`朗读完毕: ${utterance.text}`);
                resolve();
              };
            });
          }
        };

        // 开始朗读领域信息
        await new Promise((resolve) => {

          if (!this.isReading) return;
          const utterance = new SpeechSynthesisUtterance();
          utterance.lang = 'zh-CN';
          utterance.rate = 1;
          utterance.pitch = 1;
          utterance.volume = 1;

          utterance.text = `开始阅读领域 ${toReadRealm}`;
          window.speechSynthesis.speak(utterance);

          utterance.onend = () => {
            console.log(`朗读完毕:  ${utterance.text}`);
            resolve();
          };
        });

        // 递归朗读所有关键词和含义
        if (this.isReading) await speakItems(this.readTableData);

        this.isReading = false;

      }

    },
    stopReading() {
      this.isReading = false;
      window.speechSynthesis.cancel();
      console.log('朗读已停止 ');
    },
    fetchRealms() {
      getRequest('/keywords/realms')
        .then(response => {
          // 处理新的数据格式
          this.realmData = response.data;
          // 提取领域名称用于下拉选择和其他功能
          this.realms = response.data.map(item => item.realm);
          console.log('responsedata:', response.data);
          console.log('Realms:', this.realms);
        })
        .catch(error => {
          console.error('获取领域列表失败:', error);
        });

    },
    selectRealm(realm) {
      this.selectedRealm = realm;
      this.search.realm = realm;
      this.searchKeywords();
    },
    toggleExpansion() {
      this.isExpanded = !this.isExpanded;
    },
    handleSortChange({ column, prop, order }) {
      if (order === 'ascending') {
        order = 'asc';
      } else if (order === 'descending'){
        order = 'desc';
      } else{
        order = 'desc';
        prop = 'create_time';
      }
      this.sort= prop;
      this.order = order;
      this.fetchData(this.currentPage,this.pageSize,this.sort,this.order,this.search.name,this.search.realm,this.search.meaning);
    },
    fetchFinishStatus() {
      getRequest('/keywords/finishStatus')
        .then(response => {
          this.allCount = response.data.allCount;
          this.unfinishedCount = response.data.unfinishedCount;
          this.wordCount= response.data.wordCount;
        })
        .catch(error => {
          console.error('获取进度状态失败:', error);
        });
    },
    fetchKeywordOptions() {
      getRequest('/keywords/search', {
        params: {
          query: ''
        }
      })
        .then(response => {
          this.keywordOptions = response.data;
        })
        .catch(error => {
          console.error('There was an error fetching keyword options!', error);
        });
    },
    showUpdateKeywordDialog(row) {
      this.currentRow = row;
      this.editKeywordForm = {
        id: row.id,
        name: row.name,
        realm: row.realm,
        meaning: row.meaning,
        behaviorIds: row.behaviorIds.slice(),
        relationKeywordIds: row.relationKeywordIds.map(item => item.id),
        behaviorQuery: row.behaviorIds.map(id => this.searchBehaviorResults.find(item => item.id === id)?.name || ''),
        keywordQuery: row.relationKeywordIds.map(item => item.name)
      };
      this.dialogVisible = true;
    },
    confirmUpdateKeyword() {
      if (!this.editKeywordForm.name || !this.editKeywordForm.realm || !this.editKeywordForm.meaning) {
        this.$message.error('请输入所有必填项');
        return;
      }

      putRequest('/keywords', this.editKeywordForm)
        .then(response => {
          this.$message.success('关键词更新成功');
          this.dialogVisible = false;
          this.fetchData(this.currentPage,this.pageSize,this.sort,this.sortOrder,this.search.name,this.search.realm,this.search.meaning);
          this.fetchFinishStatus();
        })
        .catch(error => {
          this.$message.error('更新关键词失败');
          console.error('Error updating keyword:', error);
          this.fetchFinishStatus();
        });
    },
    showAddKeywordDialog() {
      this.addKeywordDialogVisible = true;
    },
    confirmAddKeyword() {
      if (!this.addKeywordForm.name || !this.addKeywordForm.realm || !this.addKeywordForm.meaning) {
        this.$message.error('请输入所有必填项');
        return;
      }

      postRequest('/keywords', this.addKeywordForm)
        .then(response => {
          this.$message.success('关键词添加成功');
          this.addKeywordDialogVisible = false;
          this.addKeywordForm = {
            name: '',
            realm: '',
            meaning: '',
            behaviorIds: [],
            relationKeywordIds: []
          };
          this.fetchData(this.currentPage,this.pageSize,this.sort,this.sortOrder,this.search.name,this.search.realm,this.search.meaning);
          this.fetchFinishStatus();
        })
        .catch(error => {
          this.$message.error('添加关键词失败');
          console.error('Error adding keyword:', error);
          this.fetchFinishStatus();
        });
    },
    async fuzzySearchBehavior(query) {
      if (query !== '') {
        const response = await getRequest('/keywords/fuzzySearchBehavior', { params: { name: query} });
        const results = response.data.map(item => ({
            value: item.name,
            label: item.name,
            id: item.id
          }));
        this.searchBehaviorResults = results;
      } else {
        this.searchBehaviorResults = [];
      }
    },
    async fuzzySearchKeyword(query) {
      if (query !== '') {
        const response = await getRequest('/keywords/fuzzySearchKeyword', { name: query} );
        console.log(response.data)
        const results = response.data.map(item => ({
            value: item.name,
            label: item.name,
            id: item.id
          }));
        this.searchKeywordResults = results;
        console.log(results)
        console.log(this.searchKeywordResults)
      } else {
        this.searchKeywordResults = [];
      }
    },
    handleSelectBehavior(item) {
      this.addKeywordForm.behaviorIds.push(item.id);
      this.addKeywordForm.behaviorQuery.push(item.value)
    },
    handleSelectKeyword(item) {
      console.log("item.id is "+item.id )
      console.log("item.value is "+item.value )
      console.log("item type is "+typeof(itme))


      this.addKeywordForm.relationKeywordIds.push(item.id);
      // this.addKeywordForm.keywordQueryItems.push({ id: item.id, value: item.value });
      // console.log("keyQuery:",this.addKeywordForm.keywordQueryItems)
    },
    handleEditSelectKeyword(item) {
      console.log("item.id is "+item.id )
      console.log("item.value is "+item.value )
      console.log("item type is "+typeof(itme))

      console.log("editKeywordForm.relationKeywordIds:",this.editKeywordForm.relationKeywordIds)
      this.editKeywordForm.relationKeywordIds.push(item.id);
      // this.addKeywordForm.keywordQueryItems.push({ id: item.id, value: item.value });
      // console.log("keyQuery:",this.addKeywordForm.keywordQueryItems)
    },
    removeKeyword(index) {
      const keyword = this.addKeywordForm.keywordQuery[index];
      this.addKeywordForm.relationKeywordIds = this.addKeywordForm.relationKeywordIds.filter(id => id !== keyword.id);
      this.addKeywordForm.keywordQuery.splice(index, 1);
    },
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.fetchData(this.currentPage, this.pageSize,this.sort,this.sortOrder,this.search.name,this.search.realm,this.search.meaning);
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData(this.currentPage, this.pageSize,this.sort,this.sortOrder,this.search.name,this.search.realm,this.search.meaning);
    },
    async searchKeywords() {
      try {
        const response = await postRequest('/keywords/all', {
          page:this.currentPage,
          pageSize:this.pageSize,
          name: this.search.name,
          realm: this.search.realm,
          meaning:this.search.meaning
        });
        this.tableData = response.data.items;
        this.total = response.data.total;
      } catch (error) {
        console.error('搜索失败:', error);
      }
    },
    async resetSearch() {
      this.currentPage=1;
      this.search.name='';
      this.search.realm='';
      this.search.meaning='';
      this.pageSize=10;
      this.selectedRealm='';
      try {
        const response = await postRequest('/keywords/all', {
          page:this.currentPage,
          pageSize:this.pageSize,
          name: this.search.name,
          realm: this.search.realm
        });
        this.tableData = response.data.items;
        this.total = response.data.total;
      } catch (error) {
        console.error('搜索失败:', error);
      }
    },
    addKeyword(row) {
      
    },
    async toggleReadingStatus(row, value) {
      try {
        const isReading = value ? 1 : 0;
        await putRequest(`/keywords/${row.id}/reading?isReading=${isReading}`);
        // 更新成功后更新行数据
        row.isReading = isReading;
        this.$message.success('朗读状态更新成功');
      } catch (error) {
        // 如果更新失败，恢复开关状态
        this.$message.error('更新朗读状态失败');
        console.error('Error updating reading status:', error);
      }
    }
  }
};
</script>

<style scoped>
.data-list {
  margin: 50px auto;
}
.selected-keywords {
  margin-top: 8px;
}

.el-tag + .el-tag {
  margin-left: 8px;
}

.progress-bar-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.progress-info, .reading-controls {
  display: flex;
  align-items: center;
}

.progress-info span {
  margin-right: 10px;
}

.reading-controls > * {
  margin-left: 5px; /* 控制内部元素间距 */
}

.reading-controls {
  display: flex;
  align-items: center;
  white-space: nowrap; /* 防止换行 */
}

.reading-controls > * {
  margin-left: 5px; /* 控制内部元素间距 */
}

.reading-controls span:first-child {
  margin-left: 0; /* 第一个元素不需要左边距 */
}

.custom-select-width {
  width: 200px; /* 设置你想要的宽度 */
  margin-right: 30px;
  margin-left: 30px;
}

/* 如果需要更精确地控制，可以使用以下方式 */
.el-select .el-input__inner {
  width: 200px !important; /* 强制设置输入框宽度 */
}

.read-button {
  margin-right: 20px; /* 增加右边的空隙 */
}

/* .progress-bar {
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.progress-bar {
  font-size: 16px;
  color: #333;
} */

.progress-bar span {
  padding-right: 50px; /* 添加右侧内边距 */
}

.realm-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-left: 10px;
}

.realm-item {
  background-color: #f0f0f0;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.3s, border-color 0.3s;
  display: flex;
  flex-direction: column;
  min-width: 130px;
}

.realm-item:hover {
  background-color: #e0e0e0;
  border-color: #c0c0c0;
}

.realm-item.selected {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.realm-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.realm-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.count-info {
  font-weight: 500;
}

.word-count {
  color: #666;
}

.realm-item.selected .word-count {
  color: #e0e0e0;
}

/* 新增的按钮样式 */
.toggle-button {
  background-color: transparent;
  border: none;
  color: blue;
  cursor: pointer;
  font-size: 16px;
  padding: 0;
  margin: 0 0 0 10px;
  align-self: center;
}

.realm-section {
  display: flex;
  align-items: flex-start;
  margin-top: 10px; /* 增加上方间距 */
}
</style>